import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  Alert,
  Switch,
} from 'react-native';
import { useTheme } from '../context/ThemeContext';
import { useAppContext } from '../context/AppContext';
import { createThemedStyles, getDarkThemeEnhancements, getEmptyEnhancements } from '../utils/themeStyles';
import ThemeToggle from '../components/ThemeToggle';
import { TabScreenProps } from '../types';

const SettingsScreen: React.FC<TabScreenProps<'Settings'>> = () => {
  const { theme, isDark } = useTheme();
  const { state, dispatch } = useAppContext();
  
  // 创建主题样式
  const themedStyles = createThemedStyles(theme);
  const darkEnhancements = isDark ? getDarkThemeEnhancements(theme) : getEmptyEnhancements();
  
  // 设置项数据
  const settingsData = [
    {
      title: '🎨 外观设置',
      items: [
        {
          title: '深色模式',
          description: '切换应用主题外观',
          type: 'theme-toggle',
          value: isDark,
        },
        {
          title: '字体大小',
          description: '调整应用字体大小',
          type: 'navigation',
          onPress: () => Alert.alert('提示', '字体设置功能开发中...'),
        },
      ],
    },
    {
      title: '📱 应用设置',
      items: [
        {
          title: '通知设置',
          description: '管理推送通知',
          type: 'navigation',
          onPress: () => Alert.alert('提示', '通知设置功能开发中...'),
        },
        {
          title: '数据同步',
          description: '同步您的数据到云端',
          type: 'switch',
          value: state.syncEnabled || false,
          onToggle: (value: boolean) => {
            dispatch({ type: 'TOGGLE_SYNC', payload: value });
          },
        },
        {
          title: '自动备份',
          description: '自动备份您的数据',
          type: 'switch',
          value: state.autoBackup || false,
          onToggle: (value: boolean) => {
            dispatch({ type: 'TOGGLE_AUTO_BACKUP', payload: value });
          },
        },
      ],
    },
    {
      title: '🔒 隐私与安全',
      items: [
        {
          title: '隐私政策',
          description: '查看我们的隐私政策',
          type: 'navigation',
          onPress: () => Alert.alert('隐私政策', '我们重视您的隐私，详细政策请访问官网查看。'),
        },
        {
          title: '使用条款',
          description: '查看使用条款',
          type: 'navigation',
          onPress: () => Alert.alert('使用条款', '请遵守我们的使用条款，详情请访问官网查看。'),
        },
        {
          title: '数据清理',
          description: '清理应用缓存数据',
          type: 'button',
          onPress: () => {
            Alert.alert(
              '确认清理',
              '这将清理所有缓存数据，是否继续？',
              [
                { text: '取消', style: 'cancel' },
                { 
                  text: '确认', 
                  style: 'destructive',
                  onPress: () => {
                    // 这里可以添加清理逻辑
                    Alert.alert('成功', '缓存数据已清理');
                  }
                },
              ]
            );
          },
        },
      ],
    },
    {
      title: '📞 帮助与支持',
      items: [
        {
          title: '帮助中心',
          description: '查看常见问题和帮助',
          type: 'navigation',
          onPress: () => Alert.alert('帮助中心', '如需帮助，请联系客服或查看在线文档。'),
        },
        {
          title: '意见反馈',
          description: '向我们提供宝贵意见',
          type: 'navigation',
          onPress: () => Alert.alert('意见反馈', '感谢您的反馈！请通过邮件或应用内反馈功能联系我们。'),
        },
        {
          title: '关于我们',
          description: '了解更多关于应用的信息',
          type: 'navigation',
          onPress: () => Alert.alert('关于我们', 'MyProject v1.0.0\n一个简洁高效的生产力应用'),
        },
      ],
    },
  ];
  
  // 渲染设置项
  const renderSettingItem = (item: any, index: number, isLast: boolean) => {
    return (
      <TouchableOpacity
        key={index}
        style={[
          styles.settingItem,
          !isLast && [styles.settingItemBorder, { borderBottomColor: theme.divider }],
        ]}
        onPress={item.type === 'navigation' || item.type === 'button' ? item.onPress : undefined}
        activeOpacity={item.type === 'navigation' || item.type === 'button' ? 0.7 : 1}
      >
        <View style={styles.settingTextContainer}>
          <Text style={[themedStyles.body, styles.settingTitle]}>
            {item.title}
          </Text>
          <Text style={[themedStyles.label, styles.settingDescription]}>{item.description}</Text>
        </View>
        
        {item.type === 'theme-toggle' && (
          <ThemeToggle />
        )}
        
        {item.type === 'switch' && (
          <Switch
            value={item.value}
            onValueChange={item.onToggle}
            trackColor={{ 
              false: theme.surfaceVariant, 
              true: theme.primary + '40' 
            }}
            thumbColor={item.value ? theme.primary : theme.outline}
          />
        )}
        
        {(item.type === 'navigation' || item.type === 'button') && (
          <Text style={[styles.arrow, { color: theme.outline }]}>›</Text>
        )}
      </TouchableOpacity>
    );
  };
  
  // 渲染设置组
  const renderSettingGroup = (group: any, groupIndex: number) => {
    return (
      <View
        key={groupIndex}
        style={[
          themedStyles.elevatedCard,
          styles.settingGroup,
          isDark && darkEnhancements.enhancedShadow
        ]}
      >
        <Text style={[themedStyles.subtitle, styles.groupTitle]}>{group.title}</Text>
        {group.items.map((item: any, index: number) =>
          renderSettingItem(item, index, index === group.items.length - 1)
        )}
      </View>
    );
  };
  
  return (
    <ScrollView 
      style={[themedStyles.container, styles.container]}
      showsVerticalScrollIndicator={false}
    >
      {/* 主题切换区域 */}
      <View style={[themedStyles.elevatedCard, styles.themeSection, isDark && darkEnhancements.enhancedShadow]}>
        <View style={styles.themeSectionHeader}>
          <Text style={[themedStyles.subtitle, styles.themeSectionTitle]}>
            🌙 主题设置
          </Text>
          <ThemeToggle />
        </View>
        <Text style={[themedStyles.label, styles.themeSectionDesc]}>
          {isDark ? '当前使用深色主题，护眼舒适' : '当前使用浅色主题，清新明亮'}
        </Text>
      </View>
      
      {/* 设置组 */}
      {settingsData.map((group, index) => renderSettingGroup(group, index))}
      
      {/* 退出登录按钮 */}
      <View
        style={[
          themedStyles.elevatedCard,
          styles.logoutSection,
          isDark && darkEnhancements.enhancedShadow
        ]}
      >
        <TouchableOpacity
          style={[styles.logoutButton, { backgroundColor: theme.error }]}
          onPress={() => {
            Alert.alert(
              '确认退出',
              '您确定要退出登录吗？',
              [
                { text: '取消', style: 'cancel' },
                { 
                  text: '退出', 
                  style: 'destructive',
                  onPress: () => {
                    // 这里可以添加退出登录逻辑
                    Alert.alert('已退出', '您已成功退出登录');
                  }
                },
              ]
            );
          }}
          activeOpacity={0.8}
        >
          <Text style={[styles.logoutButtonText, { color: theme.onError }]}>
            🚪 退出登录
          </Text>
        </TouchableOpacity>
      </View>
      
      {/* 版本信息 */}
      <View style={styles.versionInfo}>
        <Text style={[themedStyles.label, styles.versionText]}>
          MyProject v1.0.0
        </Text>
        <Text style={[themedStyles.label, styles.versionText]}>
          © 2024 All Rights Reserved
        </Text>
      </View>
      
      {/* 底部间距 */}
      <View style={styles.bottomSpacing} />
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  
  themeSection: {
    margin: 20,
    marginBottom: 16,
  },
  
  themeSectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 8,
  },
  
  themeSectionTitle: {
    // 样式由themedStyles.subtitle提供
  },
  
  themeSectionDesc: {
    // 样式由themedStyles.label提供
  },
  
  settingGroup: {
    marginHorizontal: 20,
    marginBottom: 16,
  },
  
  groupTitle: {
    marginBottom: 12,
  },
  
  settingItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    minHeight: 56,
  },
  
  settingItemBorder: {
    borderBottomWidth: 1,
  },
  
  settingTextContainer: {
    flex: 1,
    paddingRight: 12,
  },
  
  settingTitle: {
    fontWeight: '600',
    marginBottom: 2,
  },
  
  settingDescription: {
    // 样式由themedStyles.label提供
  },
  
  arrow: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  
  logoutSection: {
    marginHorizontal: 20,
    marginBottom: 16,
  },
  
  logoutButton: {
    paddingVertical: 14,
    paddingHorizontal: 20,
    borderRadius: 8,
    alignItems: 'center',
  },
  
  logoutButtonText: {
    fontSize: 16,
    fontWeight: '600',
  },
  
  versionInfo: {
    alignItems: 'center',
    paddingVertical: 20,
  },
  
  versionText: {
    marginBottom: 4,
  },
  
  bottomSpacing: {
    height: 20,
  },
});

export default SettingsScreen;